package echat.future.cn.echat.my.http;

import com.google.gson.JsonObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import echat.future.cn.echat.my.bean.ImageBean;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 文件上传构成器
 */
public class MultipartBuilder {
    /**
     * 单文件上传构造.
     *
     * @param file 文件
     * @param requestBody 请求体
     * @return MultipartBody
     */
    public static MultipartBody fileToMultipartBody(File file, RequestBody requestBody) {
        MultipartBody.Builder builder = new MultipartBody.Builder();

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("fileName", file.getName());

        builder.addFormDataPart("file", file.getName(), requestBody);

        builder.addFormDataPart("params", jsonObject.toString());
        builder.setType(MultipartBody.FORM);
        return builder.build();
    }



    public static List<MultipartBody.Part> filesToMultipartBodyParts(List<ImageBean> files) {
        // 上传图片信息
        List<MultipartBody.Part> parts = new ArrayList<>(files.size());
        for (int i = 1; i < files.size() ; i ++) {
            File file = new File(files.get(i).getImg());
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
            MultipartBody.Part part = MultipartBody.Part.createFormData("auth_img["+(i-1)+"]",file.getName(), requestBody);
            parts.add(part);
        }
        return parts;
    }
}
